<template>
  <div class="alarm-event-container">
    <!-- 搜索表单 -->
    <a-card :bordered="false" class="search-card">
      <div class="search-form-wrapper">
        <a-form layout="inline" :form="form" @submit="handleSearch" class="search-form">
          <!-- 基础筛选项（始终显示） -->
          <div class="form-row" :class="{ 'single-row': !needToggle }">
            <a-form-item label="" class="form-item">
              <a-range-picker
                v-decorator="['dateRange']"
                :style="{ width: '180px' }"
                format="YYYY-MM-DD"
                :placeholder="['开始日期', '结束日期']"
                @change="onDateRangeChange" />
            </a-form-item>
            <a-form-item label="" class="form-item">
              <a-select v-decorator="['workflowCode']" placeholder="请选择关联决策流" :style="{ width: '180px' }" allowClear showSearch>
                <a-select-option v-for="option in workflowOptions" :key="option.workflowCode" :value="option.workflowCode">
                  {{ option.workflowName }}
                </a-select-option>
              </a-select>
            </a-form-item>

            <!-- 扩展筛选项（当不需要切换时直接显示在第一行） -->
            <template v-if="!needToggle">
              <a-form-item label="" class="form-item">
                <a-select
                  v-decorator="['nodeType']"
                  placeholder="请选择节点类型"
                  :style="{ width: '180px' }"
                  allowClear
                  showSearch
                  @change="handleNodeTypeChange">
                  <a-select-option v-for="option in nodeTypeOptions" :key="option.nodeType" :value="option.nodeType">
                    {{ option.nodeName }}
                  </a-select-option>
                </a-select>
              </a-form-item>
              <a-form-item label="" class="form-item">
                <a-select v-decorator="['nodeId']" placeholder="请选择关联节点" :style="{ width: '180px' }" allowClear showSearch>
                  <a-select-option v-for="option in nodeOptions" :key="option.nodeId" :value="option.nodeId">
                    {{ option.nodeName }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </template>

            <!-- 操作按钮 -->
            <a-form-item label="" class="form-item action-buttons">
              <a-button icon="search" type="primary" html-type="submit" :loading="loading">
                搜索
              </a-button>
              <a-button style="margin-left: 8px" @click="handleReset">
                重置
              </a-button>
              <!-- 展开收起按钮 -->
              <a-button type="link" @click="toggleExpanded" class="expand-btn" v-show="needToggle">
                {{ expanded ? '收起' : '展开' }}
                <a-icon :type="expanded ? 'up' : 'down'" />
              </a-button>
            </a-form-item>
          </div>

          <!-- 扩展筛选项（仅在需要切换且展开时显示） -->
          <div class="form-row expanded-row" v-if="needToggle" v-show="expanded">
            <a-form-item label="" class="form-item">
              <a-select
                v-decorator="['nodeType']"
                placeholder="请选择节点类型"
                :style="{ width: '180px' }"
                allowClear
                showSearch
                @change="handleNodeTypeChange">
                <a-select-option v-for="option in nodeTypeOptions" :key="option.nodeType" :value="option.nodeType">
                  {{ option.nodeName }}
                </a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="" class="form-item">
              <a-select v-decorator="['nodeId']" placeholder="请选择关联节点" :style="{ width: '180px' }" allowClear showSearch>
                <a-select-option v-for="option in nodeOptions" :key="option.nodeId" :value="option.nodeId">
                  {{ option.nodeName }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </div>
        </a-form>
      </div>
    </a-card>

    <!-- 数据表格 -->
    <a-card :bordered="false" class="table-card">
      <div class="table-page-search-wrapper">
        <a-table
          :columns="columns"
          :data-source="dataSource"
          :pagination="pagination"
          :loading="loading"
          :scroll="{ x: 1400 }"
          row-key="id"
          @change="handleTableChange">
          <!-- 规则名称列 -->
          <template slot="ruleName" slot-scope="text">
            <span>{{ text || '--' }}</span>
          </template>

          <!-- 告警时间列 -->
          <template slot="lastAlarmTime" slot-scope="text">
            <span>{{ text }}</span>
          </template>

          <!-- 关联决策流列 -->
          <template slot="workflowName" slot-scope="text">
            <span>{{ text }}</span>
          </template>

          <!-- 关联节点列 -->
          <template slot="nodeName" slot-scope="text">
            <span>{{ text || '--' }}</span>
          </template>

          <!-- 当前告警值列 -->
          <template slot="lastAlarmValue" slot-scope="text, record">
            <div class="alarm-value-list">
              <div v-for="(item, index) in record.lastAlarmValue" :key="index" class="alarm-value-item">
                <span class="item-index">{{ index + 1 }}、</span>
                <span class="index-name">{{ item.indexName }}:</span>
                <span class="index-value">{{ item.indexValue }}</span>
                <!-- <a-tag v-if="item.hit" color="red" size="small">命中</a-tag> -->
              </div>
            </div>
          </template>

          <!-- 连续告警次数列 -->
          <template slot="successionAlarmCount" slot-scope="text">
            <span>{{ text }}</span>
          </template>

          <!-- 状态列 -->
          <template slot="status" slot-scope="text">
            <div class="status-item">
              <span v-if="text === 1" class="status-dot status-pending"></span>
              <span v-else-if="text === 2" class="status-dot status-suspended"></span>
              <span v-else-if="text === 3" class="status-dot status-completed"></span>
              <span v-else class="status-dot status-default"></span>
              <span class="status-text">
                <span v-if="text === 1">待处理</span>
                <span v-else-if="text === 2">挂起中</span>
                <span v-else-if="text === 3">结束</span>
                <span v-else>{{ text }}</span>
              </span>
            </div>
          </template>

          <!-- 操作列 -->
          <template slot="action" slot-scope="text, record">
            <a @click="handleDetail(record)" v-if="$hasPermission('detail')">详情</a>
            <a-divider type="vertical" v-if="record.status === 1 || record.status === 2" />
            <a @click="handleProcess(record)" v-if="record.status === 1 && $hasPermission('hangUp')">挂起</a>
            <a-divider type="vertical" v-if="record.status === 1 || record.status === 2" />
            <a @click="handleComplete(record)" v-if="(record.status === 1 || record.status === 2) && $hasPermission('end')">结束</a>
          </template>
        </a-table>
      </div>
    </a-card>

    <!-- 操作弹窗 -->
    <a-modal
      :title="operationType === 'hangUp' ? '挂起' : '结束'"
      :visible="operationVisible"
      @ok="handleOperationOk"
      @cancel="handleOperationCancel"
      :confirmLoading="operationLoading"
      okText="确定"
      cancelText="取消">
      <a-form :form="operationForm" layout="vertical">
        <a-form-item :label="operationType === 'hangUp' ? '挂起描述' : '结束描述'">
          <a-textarea
            v-decorator="['description', { rules: [{ required: true, message: operationType === 'hangUp' ? '请输入挂起描述' : '请输入结束描述' }] }]"
            :placeholder="operationType === 'hangUp' ? '请输入挂起描述' : '请输入结束描述'"
            :rows="4" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script>
import { alarmEventPage, relationNodeConfig, relationWorkflow, alarmEventHangUp, alarmEventProcess } from '@/api/alarmEvent'
import moment from 'moment'

export default {
  name: 'AlarmEvent',
    beforeRouteEnter(to, from, next) {
    if (from.path === '/403') {
      window.location.reload()
      return
    }
    next((vm) => {
      if (!vm.$hasPermission('query')) {
        vm.$router.push({ path: '/403' })
      }
    })
  },
  data() {
    return {
      form: this.$form.createForm(this),
      loading: false,
      expanded: false, // 控制筛选器展开收起状态
      needToggle: false, // 是否需要显示展开收起按钮
      containerWidth: 0, // 容器宽度
      dataSource: [],
      nodeTypeOptions: [],
      nodeOptions: [], // 关联节点选项
      selectedNodeType: '', // 当前选中的节点类型
      nodeConfigData: [], // 完整的节点配置数据
      workflowOptions: [],
      // 操作弹窗
      operationVisible: false,
      operationForm: this.$form.createForm(this, { name: 'operation' }),
      operationLoading: false,
      currentRecord: null,
      operationType: '', // 'hangUp' 或 'process'
      pagination: {
        current: 1,
        pageSize: 10,
        total: 0,
        showSizeChanger: true,
        showQuickJumper: true,
        showTotal: (total, range) => `共 ${total} 条记录，第 ${range[0]}-${range[1]} 条`
      },
      queryParams: {
        curPage: 1,
        pageSize: 10
      },
      columns: [
        {
          title: '规则名称',
          dataIndex: 'ruleName',
          key: 'ruleName',
          width: 150,
          scopedSlots: { customRender: 'ruleName' }
        },
        {
          title: '告警时间',
          dataIndex: 'lastAlarmTime',
          key: 'lastAlarmTime',
          width: 160,
          scopedSlots: { customRender: 'lastAlarmTime' }
        },
        {
          title: '关联决策流',
          dataIndex: 'workflowName',
          key: 'workflowName',
          width: 120,
          scopedSlots: { customRender: 'workflowName' }
        },
        {
          title: '关联节点',
          dataIndex: 'nodeName',
          key: 'nodeName',
          width: 120,
          scopedSlots: { customRender: 'nodeName' }
        },
        {
          title: '当前告警数据',
          dataIndex: 'lastAlarmValue',
          key: 'lastAlarmValue',
          width: 300,
          scopedSlots: { customRender: 'lastAlarmValue' }
        },
        {
          title: '连续告警次数',
          dataIndex: 'successionAlarmCount',
          key: 'successionAlarmCount',
          width: 140,
          scopedSlots: { customRender: 'successionAlarmCount' }
        },
        {
          title: '状态',
          dataIndex: 'status',
          key: 'status',
          width: 100,
          scopedSlots: { customRender: 'status' }
        },
        {
          title: '操作',
          key: 'action',
          width: 200,
          fixed: 'right',
          scopedSlots: { customRender: 'action' }
        }
      ]
    }
  },
  mounted() {
    this.fetchNodeTypeOptions()
    this.fetchWorkflowOptions()
    this.fetchData()
    this.checkContainerWidth()
    window.addEventListener('resize', this.handleResize)
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize)
  },
  methods: {
    // 获取数据
    async fetchData() {
      this.loading = true
      try {
        const params = {
          curPage: this.queryParams.curPage,
          pageSize: this.queryParams.pageSize
        }

        // 添加可选参数
        if (this.queryParams.startTime) {
          params.startTime = this.queryParams.startTime
        }
        if (this.queryParams.endTime) {
          params.endTime = this.queryParams.endTime
        }
        if (this.queryParams.nodeType) {
          params.nodeType = this.queryParams.nodeType
        }
        if (this.queryParams.nodeId) {
          params.nodeId = this.queryParams.nodeId
        }
        if (this.queryParams.workflowCode) {
          params.workflowCode = this.queryParams.workflowCode
        }

        const response = await alarmEventPage(params)
        if (response.success) {
          this.dataSource = response.data.contents
          this.pagination.total = response.data.total
          this.pagination.current = response.data.curPage
        } else {
          this.$message.error(response.message || '获取数据失败')
        }
      } catch (error) {
        console.error('获取告警事件数据失败:', error)
        this.$message.error('获取数据失败')
      } finally {
        this.loading = false
      }
    },

    // 搜索
    handleSearch(e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (!err) {
          this.queryParams = {
            curPage: 1,
            pageSize: this.pagination.pageSize,
            ...values
          }
          this.pagination.current = 1
          this.fetchData()
        }
      })
    },

    // 重置
    handleReset() {
      this.form.resetFields()
      this.queryParams = {
        curPage: 1,
        pageSize: this.pagination.pageSize
      }
      this.pagination.current = 1
      this.fetchData()
    },

    // 表格变化
    handleTableChange(pagination) {
      this.pagination.current = pagination.current
      this.pagination.pageSize = pagination.pageSize
      this.queryParams.curPage = pagination.current
      this.queryParams.pageSize = pagination.pageSize
      this.fetchData()
    },

    // 日期范围变化
    onDateRangeChange(dates, dateStrings) {
      if (dates && dates.length === 2) {
        this.queryParams.startTime = moment(dates[0]).valueOf()
        this.queryParams.endTime = moment(dates[1]).valueOf()
      } else {
        delete this.queryParams.startTime
        delete this.queryParams.endTime
      }
    },

    // 查看详情
    handleDetail(record) {
      this.$router.push({
        path: '/heimdallr/alarmEvent/detail',
        query: {
          id: record.id
        }
      })
    },

    // 处理告警 - 挂起
    handleProcess(record) {
      this.currentRecord = record
      this.operationType = 'hangUp'
      this.operationVisible = true
    },

    // 完成告警 - 结束
    handleComplete(record) {
      this.currentRecord = record
      this.operationType = 'process'
      this.operationVisible = true
    },

    // 操作确认
    handleOperationOk() {
      this.operationForm.validateFields(async (err, values) => {
        if (!err) {
          this.operationLoading = true
          try {
            const params = {
              id: this.currentRecord.id,
              description: values.description
            }

            let response
            let successMessage
            let errorMessage

            if (this.operationType === 'hangUp') {
              response = await alarmEventHangUp(params)
              successMessage = '挂起成功'
              errorMessage = '挂起失败'
            } else {
              response = await alarmEventProcess(params)
              successMessage = '结束成功'
              errorMessage = '结束失败'
            }

            if (response.success) {
              this.$message.success(successMessage)
              this.operationVisible = false
              this.operationForm.resetFields()
              this.fetchData() // 刷新数据
            } else {
              this.$message.error(response.message || errorMessage)
            }
          } catch (error) {
            console.error(`${this.operationType === 'hangUp' ? '挂起' : '结束'}失败:`, error)
            this.$message.error(this.operationType === 'hangUp' ? '挂起失败' : '结束失败')
          } finally {
            this.operationLoading = false
          }
        }
      })
    },

    // 操作取消
    handleOperationCancel() {
      this.operationVisible = false
      this.operationForm.resetFields()
    },

    // 获取节点类型选项
    async fetchNodeTypeOptions() {
      try {
        const response = await relationNodeConfig()
        if (response.success && response.data) {
          // 保存完整的节点配置数据
          this.nodeConfigData = response.data
          // 提取第一级的nodeType和nodeName
          this.nodeTypeOptions = response.data.map(item => ({
            nodeType: item.nodeType,
            nodeName: item.nodeName
          }))
        } else {
          console.error('获取节点类型失败:', response.message)
        }
      } catch (error) {
        console.error('获取节点类型选项失败:', error)
      }
    },

    // 处理节点类型变化
    handleNodeTypeChange(nodeType) {
      this.selectedNodeType = nodeType
      // 清空关联节点选择
      this.form.setFieldsValue({ nodeId: undefined })

      if (nodeType) {
        // 根据选中的节点类型找到对应的关联节点列表
        const selectedConfig = this.nodeConfigData.find(item => item.nodeType === nodeType)
        if (selectedConfig && selectedConfig.nodeList) {
          this.nodeOptions = selectedConfig.nodeList
        } else {
          this.nodeOptions = []
        }
      } else {
        this.nodeOptions = []
      }
    },

    // 获取关联决策流选项
    async fetchWorkflowOptions() {
      try {
        const response = await relationWorkflow()
        if (response.success && response.data) {
          // 提取workflowCode和workflowName
          this.workflowOptions = response.data.map(item => ({
            workflowCode: item.workflowCode,
            workflowName: item.workflowName
          }))
        } else {
          console.error('获取关联决策流失败:', response.message)
        }
      } catch (error) {
        console.error('获取关联决策流选项失败:', error)
      }
    },

    // 切换筛选器展开收起状态
    toggleExpanded() {
      this.expanded = !this.expanded
    },

    // 处理窗口大小变化
    handleResize() {
      this.checkContainerWidth()
    },

    // 检查容器宽度，决定是否需要展开收起功能
    checkContainerWidth() {
      this.$nextTick(() => {
        const container = this.$el.querySelector('.search-form')
        if (container) {
          this.containerWidth = container.offsetWidth

          // 临时设置为不需要切换模式来测量所有项目的宽度
          const originalNeedToggle = this.needToggle
          this.needToggle = false

          this.$nextTick(() => {
            // 计算所有筛选项在一行时的总宽度
            const allItems = container.querySelectorAll('.form-row:first-child .form-item')
            let totalWidth = 0
            allItems.forEach(item => {
              totalWidth += item.offsetWidth + 16 // 16px是margin-right
            })

            const availableWidth = this.containerWidth - 40 // 预留一些边距

            if (totalWidth <= availableWidth) {
              // 宽度足够，不需要展开收起功能，所有项目一行显示
              this.needToggle = false
              this.expanded = true
            } else {
              // 宽度不足，需要展开收起功能
              this.needToggle = true
              // 默认收起状态
              this.expanded = false
            }
          })
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.alarm-event-container {
  padding: 24px;
  background-color: #f0f2f5;
  min-height: 100vh;

  .search-card {
    margin-bottom: 24px;

    .search-form-wrapper {
      .search-form {
        .form-row {
          display: flex;
          flex-wrap: wrap;
          align-items: center;
          margin-bottom: 16px;

          &:last-child {
            margin-bottom: 0;
          }

          .form-item {
            margin-right: 16px;
            margin-bottom: 8px;

            &.action-buttons {
              display: flex;
              align-items: center;

              .expand-btn {
                margin-left: 16px;
                padding: 4px 8px;
                color: #1890ff;

                &:hover {
                  color: #40a9ff;
                }
              }
            }
          }

          // 当不需要切换时，第一行和扩展行合并为一行
          &:first-child {
            &.single-row {
              .form-item {
                flex-shrink: 0;
              }
            }
          }
        }

        .expanded-row {
          border-top: 1px solid #f0f0f0;
          padding-top: 16px;
          margin-top: 8px;
          animation: slideDown 0.3s ease-in-out;

          // 当不需要切换时，移除边框和动画，并与第一行合并显示
          &.no-toggle {
            border-top: none;
            padding-top: 0;
            margin-top: -16px; // 负边距使其与第一行合并
            margin-left: 0;
            animation: none;

            .form-item {
              display: inline-flex;
            }
          }
        }
      }
    }
  }

  .table-card {
    .alarm-value-list {
      .alarm-value-item {
        display: flex;
        align-items: center;
        margin-bottom: 4px;
        font-size: 12px;

        .item-index {
          color: #999;
          font-size: 12px;
          margin-right: 4px;
          font-weight: normal;
        }

        .index-name {
          color: #666;
          margin-right: 4px;
        }

        .index-value {
          font-weight: 500;
          margin-right: 8px;
        }
      }
    }

    .status-item {
      display: flex;
      align-items: center;

      .status-dot {
        width: 8px;
        height: 8px;
        border-radius: 50%;
        margin-right: 8px;
        display: inline-block;

        &.status-pending {
          background-color: #52c41a; // 绿色 - 待处理
        }

        &.status-suspended {
          background-color: #fa8c16; // 橙色 - 挂起中
        }

        &.status-completed {
          background-color: #8c8c8c; // 灰色 - 结束
        }

        &.status-default {
          background-color: #1890ff; // 蓝色 - 默认
        }
      }

      .status-text {
        font-size: 14px;
        color: #333;
      }
    }
  }
}

// 动画效果
@keyframes slideDown {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

// 响应式布局
@media (max-width: 1500px) {
  .alarm-event-container {
    .search-card {
      .search-form-wrapper {
        .search-form {
          .form-row {
            .form-item {
              margin-bottom: 12px;
            }
          }
        }
      }
    }
  }
}

@media (max-width: 1200px) {
  .alarm-event-container {
    .search-card {
      .search-form-wrapper {
        .search-form {
          .form-row {
            .form-item {
              margin-bottom: 16px;
            }
          }
        }
      }
    }
  }
}
</style>
